﻿using System;
using System.Text;
using System.Threading;
using Iorz.DomainSearch.Utils.Tools;

namespace Iorz.DomainSearch.Utils.Provider
{
    public class AliyunProvider : IProvider
    {
        private int mTryCount = 1;

        private string mLog = "Error_Aliyun.log";

        public string GetName()
        {
            return "阿里云万网";
        }

        public bool Search(string domain, out bool isAvail)
        {
            return CheckDomainAvail(domain, out isAvail);
        }

        private bool CheckDomainAvail(string domain, out bool isAvail)
        {
            isAvail = false;

            var response = HttpHelper.GetHtml(new HttpHelper.HttpRequest()
            {
                Method = HttpHelper.HttpMethod.GET,
                UserAgent = "Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
                Url = GetUrl(domain)
            });

            if (response.Exception == null
                && !string.IsNullOrEmpty(response.Html)
                && response.Html.IndexOf("\"success\":\"true\"") != -1)
            {
                if (response.Html.IndexOf("\"avail\":1") != -1)
                {
                    Tracker.Log("domain.log", domain);
                    isAvail = true;
                }

                return true;
            }

            if (response.Exception == null)
                Tracker.Log(mLog, response.Html);
            else
                Tracker.Log(mLog, response.Exception.Message);

            if (mTryCount <= 3)
            {
                mTryCount++;
                Thread.Sleep(3000);
                return CheckDomainAvail(domain, out isAvail);
            }

            return false;
        }

        private string GetUrl(string domain)
        {
            return $"https://checkapi.aliyun.com/check/checkdomain?callback=jQuery111108252368259687763_{DateHelper.GetTimestamp4Millisecond()}&domain={domain}&token=check-web-hichina-com%3A{GetToken()}&_={DateHelper.GetTimestamp4Millisecond()}";
        }

        private string GetToken()
        {
            var data = new string[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
              , "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

            var result = new StringBuilder();
            var length = data.Length;
            var random = new Random();
            for (var i = 0; i < 32; i++)
            {
                result.Append(data[random.Next(0, length)]);
            }
            return result.ToString();
        }
    }
}
